package bold.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * RedisSessionDao，以Redis持久化方式做Session共享，无需配置即可支持集群
 */
@Slf4j
public class RedisSessionDao extends AbstractSessionDAO {

    private RedisTemplate redisTemplate;

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        redisTemplate.opsForValue().set(session.getId(), session, session.getTimeout(), TimeUnit.MILLISECONDS);
        log.info("shiro-trace====session doCreate id={},Timeout={}",sessionId,session.getTimeout());
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        log.info("shiro-trace====session doReadSession {}",sessionId);
        return sessionId == null ? null : (Session) redisTemplate.opsForValue().get(sessionId);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        log.info("shiro-trace====session update id={},Timeout={}",session.getId(),session.getTimeout());
        if (session != null && session.getId() != null) {
            redisTemplate.opsForValue().set(session.getId(), session, session.getTimeout(), TimeUnit.MILLISECONDS);
        }
    }

    @Override
    public void delete(Session session) {
        log.info("shiro-trace====session delete {}",session);
        if (session != null && session.getId() != null) {
            redisTemplate.opsForValue().getOperations().delete(session.getId());
        }
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set keys = redisTemplate.keys(ShiroSessionIdGenerator.PREFIX+"*");
        log.info("shiro-trace====session getActiveSessions keys={}", keys);
        return keys;
    }

}